<template>
  <div>
    <el-dialog
      v-model="visible"
      :title="!dataForm.userId ? $t('sysManagement.add') : $t('crud.editTitle')"
      :close-on-click-modal="false"
      class="dialog-add-or-update"
      width="60%"
    >
      <el-form
        ref="dataFormRef"
        :model="dataForm"
        :label-width="$t('language') === 'English' ? '130px' : '80px'"
        @submit.prevent
        @keyup.enter="onSubmit()"
      >
        <el-divider content-position="left">
          <h3>{{ $t('user.userInformation') }}</h3>
        </el-divider>
        <el-container>
          <el-aside
            width="240px"
            style="margin-top: 20px"
          >
            <el-form-item
              :label="$t('publics.profilePicture')"
              prop="pic"
            >
              <img
                v-if="!dataForm.pic"
                src="~@/assets/img/userImg.jpg"
                alt=""
                width="130"
                height="130"
              >
              <img
                v-else
                :src="resourcesUrl +dataForm.pic"
                class="image"
                alt=""
                width="130"
                height="130"
              >
            </el-form-item>
          </el-aside>
          <el-container>
            <el-main>
              <el-row>
                <el-col
                  :span="7"
                  justify="start"
                >
                  <el-form-item
                    :label="$t('users.name') + ':'"
                    prop="nickName"
                  >
                    <span v-if="nameVisible">{{ dataForm.nickName }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item
                    :label="$t('publics.status') + ':'"

                    prop="status"
                  >
                    <span v-if="dataForm.status === 0">{{ $t('publics.disable') }}</span>
                    <span v-if="dataForm.status === 1">{{ $t('publics.normal') }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="9">
                  <el-form-item
                    :label="$t('user.registrationTime') + ':'"
                    prop="userRegtime"
                  >
                    <span>{{ dataForm.userRegtime }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-main>
            <el-footer>
              <div
                v-if="isAuth('admin:coupon:sendUserCoupon')"
                class="default-btn primary-btn"
                @click="onUpdateCoupon()"
              >
                {{ $t('user.sendCoupons') }}
              </div>
              <div
                class="default-btn primary-btn"
                @click="onUpdateUserInfo()"
              >
                {{ $t('components.editName') + '/' + $t('product.status') }}
              </div>
              <div
                class="default-btn primary-btn"
                @click="onUpdateTags()"
              >
                {{ $t('user.tagging') }}
              </div>
            </el-footer>
          </el-container>
        </el-container>
        <el-form-item
          :label="$t('user.customerLabel')"
          prop="userTagParam"
        >
          <div v-if="userTag.length > 0">
            <el-tag
              v-for="tag in userTag"
              :key="tag.tagId"
              :closable="tag.tagType === 0"
              :disable-transitions="false"
              @close="onHandleClose(tag)"
            >
              {{ tag.tagName }}
            </el-tag>
          </div>
        </el-form-item>
        <!-- 账户资产 -->
        <el-divider content-position="left">
          <h3>{{ $t('user.accountAssets') }}</h3>
        </el-divider>
        <el-container>
          <el-main>
            <div>
              <h4>{{ $t('user.accountWallet') }}</h4>
              <br>
              <div>
                <span>{{ $t('user.currentBalance') }}：{{ dataForm.sumBalance }}</span>
                <span style="margin-left: 60px">{{ $t('user.cumulativeBalances') }}：{{ dataForm.currentBalance }}</span>
                <br>
                <span>{{ $t('user.rechargeAmount') }}：{{ dataForm.rechargeAmount }}</span>
                <span style="margin-left: 60px">{{ $t('user.rechargeTimes') }}：{{ dataForm.rechargeTimes }}</span>
              </div>
              <br>
            </div>
            <br>
            <div>
              <h4>{{ $t('order.integral') }}</h4>
              <br>
              <div>
                <span>{{ $t('user.currentScore') }}：{{ dataForm.score }}</span>
                <span style="margin-left: 60px">{{ $t('user.cumulativeScore') }}：{{ dataForm.sumScore }}</span>
              </div>
              <br>
            </div>
            <br>
            <div>
              <h4>
                {{ $t('user.coupons') }}
                <el-popover
                  placement="top"
                  width="200"
                  trigger="hover"
                  :content="$t('user.couponTip3')"
                >
                  <template #reference>
                    <el-icon><QuestionFilled /></el-icon>
                  </template>
                </el-popover>
              </h4>
              <br>
              <div>
                <span>{{ $t('user.notUsed') }}：{{ couponUserParam.couponUsableNums }}&nbsp;&nbsp;{{
                  $t('marketing.piece')
                }}</span>
                <span style="margin-left: 60px">{{ $t('user.used') }}：{{ couponUserParam.couponUsedNums }}&nbsp;&nbsp;{{
                  $t('marketing.piece')
                }}</span>
                <br>
                <span>{{ $t('user.invalid') }}：{{ couponUserParam.couponExpiredNums }}&nbsp;&nbsp;{{
                  $t('marketing.piece')
                }}</span>
              </div>
              <br>
            </div>
          </el-main>
        </el-container>
        <el-divider content-position="left">
          <h3>{{ $t('user.otherInfo') }}</h3>
        </el-divider>
      </el-form>
      <div>
        <el-tabs>
          <el-tab-pane :label="$t('user.distributionInfo')">
            <div>
              <span>{{ $t('distributionMsg.invitees') }}：{{
                distributionUser.parentName ? distributionUser.parentName : '---'
              }}</span>
              <span style="margin-left: 40px">{{ $t('user.distributionTime') }}：{{
                distributionUser.bindTime ? distributionUser.bindTime : '---'
              }}</span>
              <span
                v-if="distributionUser.state == null"
                style="margin-left: 20px"
              >{{ $t('user.status') }}：{{ '---' }}</span>
              <span
                v-else-if="distributionUser.state === -1"
                style="margin-left: 20px"
              >{{ $t('user.status') }}：{{ $t('distribUserWallet.ban') }}</span>
              <span
                v-else-if="distributionUser.state > -1"
                style="margin-left: 20px"
              >{{ $t('user.status') }}：{{
                [
                  $t('product.pendingReview'),
                  $t('publics.normal'),
                  $t('distribUserWallet.cleared'),
                  $t('productComm.auditFailed')
                ][distributionUser.state]
              }}</span>
            </div>
          </el-tab-pane>
          <el-tab-pane :label="$t('user.tradeDetails')">
            <trade-detail ref="tradeDetailRef" />
          </el-tab-pane>
          <el-tab-pane :label="$t('user.scoreDetails')">
            <score-detail ref="scoreDetailRef" />
          </el-tab-pane>
          <el-tab-pane :label="$t('user.balanceDetails')">
            <balance-detail ref="balanceDetailRef" />
          </el-tab-pane>
          <el-tab-pane :label="$t('user.couponDetails')">
            <coupon-detail ref="couponDetailRef" />
          </el-tab-pane>
          <el-tab-pane :label="$t('user.growthLog')">
            <growth-detail ref="growthDetailRef" />
          </el-tab-pane>
        </el-tabs>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <div
            class="default-btn primary-btn"
            type="primary"
            @click="onSubmit()"
          >
            {{ $t('remindPop.confirm') }}
          </div>
        </div>
      </template>
    </el-dialog>
    <!-- 送优惠券弹窗 -->
    <update-user-coupon
      v-if="updateCouponVisible"
      ref="updateCouponRef"
      :get-way="1"
      @refresh-data-list="refreshChange"
    />
    <!-- 打标签弹窗 -->
    <update-user-tags
      v-if="updateTagsVisible"
      ref="updateTagsRef"
      @refresh-data-list="refreshChange"
    />
    <!-- 修改用户基本信息 -->
    <UpdateUserInfo
      v-if="updateUserInfoVisible"
      ref="updateUserInfoRef"
      @refresh-user-info="refreshInfo"
    />
  </div>
</template>

<script setup>
import UpdateUserCoupon from './components/update-coupon.vue'
import UpdateUserInfo from './components/update-info.vue'
import UpdateUserTags from './components/update-tags.vue'
import TradeDetail from './components/trade-detail.vue'
import ScoreDetail from './components/score-detail.vue'
import BalanceDetail from './components/balance-detail.vue'
import CouponDetail from './components/coupon-detail.vue'
import GrowthDetail from './components/growth-detail.vue'
import { isAuth } from '@/utils/index'
const resourcesUrl = import.meta.env.VITE_APP_RESOURCES_URL

const emit = defineEmits(['refreshDataList'])

const isSubmit = ref(false)
const dataFormRef = ref(null)
const dataForm = ref({
  userId: 0,
  nickName: '',
  pic: '',
  status: 1
})
const defaultCouponUserParam = {
  couponUsableNums: 0,
  couponUsedNums: 0,
  couponExpiredNums: 0
}
const couponUserParam = ref({
  couponUsableNums: 0,
  couponUsedNums: 0,
  couponExpiredNums: 0
})
const userTag = ref([{ agId: 0, tagName: null }])
const visible = ref(false)

const init = id => {
  dataForm.value.userId = id || 0
  visible.value = true
  isSubmit.value = false
  onClearVueData()
  nextTick(() => {
    dataFormRef.value?.resetFields()
  })
  if (dataForm.value.userId) {
    if (isSubmit.value) {
      return false
    }
    isSubmit.value = true
    http({
      url: http.adornUrl(`/admin/user/info/${dataForm.value.userId}`),
      method: 'get',
      params: http.adornParams()
    })
      .then(({ data }) => {
        dataForm.value = data
        couponUserParam.value = dataForm.value.couponUserParam
        userTag.value = dataForm.value.userTagParam
        onGetDistribution()
        onInitTradeDetail(dataForm.value.userId)
        onItScoreDetail(dataForm.value.userId)
        onInitBalanceDetail(dataForm.value.userId)
        onInitCouponDetail(dataForm.value.userId)
        onInitGrowthDetail(dataForm.value.userId)
      })
      .catch(() => {
        isSubmit.value = false
      })
  }
}
// 修改后刷新
const refreshChange = () => {
  init(dataForm.value.userId)
}
// 移除标签
const onHandleClose = tag => {
  http({
    url: http.adornUrl('/user/userTag/deleteUserTag'),
    method: 'delete',
    data: http.adornData({
      userId: dataForm.value.userId,
      userTagId: tag.tagId
    })
  }).then(() => {
    init(dataForm.value.userId)
  })
}
// 表单提交
const statusVisible = ref(true)
const nameVisible = ref(true)
const page = ref({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const onSubmit = () => {
  dataFormRef.value?.validate(valid => {
    if (valid) {
      http({
        url: http.adornUrl('/admin/user'),
        method: 'put',
        data: http.adornData({
          userId: dataForm.value.userId,
          nickName: dataForm.value.nickName,
          status: dataForm.value.status
        })
      })
        .then(() => {
          init(dataForm.value.userId)
          nameVisible.value = true
          statusVisible.value = true
          visible.value = false
          emit('refreshDataList', page.value)
        })
        .catch(() => {
          isSubmit.value = false
        })
    }
  })
}
// 打标签
const updateTagsVisible = ref(false)
const updateTagsRef = ref(null)
const onUpdateTags = id => {
  const ids = id ? [id] : [dataForm.value.userId]
  updateTagsVisible.value = true
  nextTick(() => {
    updateTagsRef.value?.init(ids)
  })
}

// 送优惠券
const updateCouponVisible = ref(false)
const updateCouponRef = ref(null)
const onUpdateCoupon = id => {
  const ids = id ? [id] : [dataForm.value.userId]
  updateCouponVisible.value = true
  nextTick(() => {
    updateCouponRef.value?.init(ids)
  })
}
// 送优惠券
const updateUserInfoVisible = ref(false)
const updateUserInfoRef = ref(null)
const onUpdateUserInfo = () => {
  updateUserInfoVisible.value = true
  nextTick(() => {
    updateUserInfoRef.value?.init(dataForm.value)
  })
}

// 清空数据
const onClearVueData = () => {
  Object.assign(couponUserParam.value, defaultCouponUserParam)
}
// 获取分销员信息
// 分销信息
const distributionUser = ref({
  parentName: null,
  bindTime: null,
  state: null
})
const onGetDistribution = () => {
  distributionUser.value.bindTime = null
  distributionUser.value.state = null
  distributionUser.value.parentName = null
  http({
    url: http.adornUrl(`/distribution/distributionUser/getInfo/${dataForm.value.userId}`),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    if (data) {
      distributionUser.value.bindTime = data.bindTime
      distributionUser.value.state = data.state
      if (data.parentDistributionUser) {
        distributionUser.value.parentName = data.parentDistributionUser.nickName
      }
    }
  })
}
// 调用交易信息组件方法
const tradeDetailRef = ref(null)
const onInitTradeDetail = id => {
  tradeDetailRef.value?.init(id)
}
// 调用积分详情组件方法
const scoreDetailRef = ref(null)
const onItScoreDetail = id => {
  scoreDetailRef.value?.init(id)
}
// 余额明细
const balanceDetailRef = ref(null)
const onInitBalanceDetail = id => {
  balanceDetailRef.value?.init(id)
}
// 优惠券明细
const couponDetailRef = ref(null)
const onInitCouponDetail = id => {
  couponDetailRef.value?.init(id)
}
// 调用成长值记录组件方法
const growthDetailRef = ref(null)
const onInitGrowthDetail = id => {
  growthDetailRef.value?.init(id)
}
// 修改名称或者状态完成后刷新详情
const refreshInfo = () => {
  init(dataForm.value.userId)
  emit('refreshDataList', page.value)
}
defineExpose({ init })
</script>
<style lang="scss" scoped>
:deep(.dialog-add-or-update) {
  .el-tabs__content {
    overflow: auto;
  }
  .el-tag {
    margin-left: 10px;
  }
}
</style>
